#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define TOKENIZER(toBeParsed, spot, separator)  char *spot = NULL; \
                                                for(spot = strtok(toBeParsed, separator); spot != NULL; spot = strtok(NULL, separator))

#define READLINES(file, line)                   char line[100]; \
                                                while(fgets(line, 100, file) != NULL)
#define PROTECTED "freeze-safe."

#define LOG fprintf(thawFile,

//Prototypes
void makeChange(int u_id, char *origLocation, int newFile, int regularFile, FILE *thawFile);

int main(){
  FILE *file = fopen(PROTECTED "logFile.txt", "r");
	FILE *thawFile = fopen("thawFile.txt", "a");

  int part = 0;

  //For each line of the file
  int u_id, newFile, regularFile;
  char *origLocation;

  READLINES(file, line){
		LOG"Reading line %s", line);
    TOKENIZER(line, piece, "\t"){
			LOG"\tReading piece %s", piece);
      switch(part % 4){
        //u_id
        case 0:
          u_id = atoi(piece);
          break;

        //origLocation
        case 1:
          origLocation = piece;
          break;

        //newFile
        case 2:
          newFile = atoi(piece);
          break;

        //regularFile
        case 3:
          regularFile = atoi(piece);

          //Destroy newline character
          char *newLine = NULL;
          if((newLine = strstr(piece, "\n")) != NULL){
            *newLine = '\0';
          }

          break;
        default:
          LOG"Error: There were too many pieces: %s\n", line);
          exit(1);
      }
      
      //Next part of line
      part++;
    }

    makeChange(u_id, origLocation, newFile, regularFile, thawFile);
  }

  fclose(file);
  fclose(thawFile);

  return 0;
}

void makeChange(int u_id, char *origLocation, int newFile, int regularFile, FILE *thawFile){
  //Regular file?
  if(regularFile){
    //New file?
    if(newFile){
      // Delete file at origLocation
			LOG"Removing new file at %s\n", origLocation);
      if(remove(origLocation)) LOG"Error removing new file at %s\n", origLocation);

    //Modified file
    } else {

			LOG"Removing modified file at %s\n", origLocation);
      // Delete modified file at origLocation
      if(remove(origLocation)) LOG"Error removing modified file at %s\n", origLocation);

      // Copy backup to origLocation
      char u_idString[128];
      sprintf(u_idString, PROTECTED "%d", u_id);

			LOG"Moving backed up modified file from %s to %s\n", u_idString, origLocation);
      if(rename(u_idString, origLocation)) LOG"Error moving modifed file from %s to %s\n", u_idString, origLocation);
      //
    }

  //Directory
  } else {
    /* Remove directory */
  }
}

